#include "pixelgraphics.h"
#include "graphicsmode.h"
#include "realthunk.h"

namespace graphics_mode
{
  extern TYPE active_type;
}

namespace pixel_graphics
{
  void init()
  {
  }

  uint rows()
  { return 200; }

  uint cols()
  { return 320; }

  void clear()
  {
    for (uint i = 0; i < rows()*cols(); ++i)
      put_pixel(BLACK, i);
  }

  void set_pixel_graphics_mode()
  {
    real_thunk::set_video_mode_params gm;
    gm.hdr.func_type = real_thunk::SET_VIDEO_MODE;
    gm.mode = 0x13;
    real_thunk::func((void*)(&gm), sizeof(gm));

    graphics_mode::active_type = graphics_mode::PIXEL;

    // Wait until graphics card is ready?
  }

  void put_pixel(color clr, uint position)
  {
#if 0
    put_pixel(color, point2d(position % cols(), position / cols()));
#else
    if (graphics_mode::active_type != graphics_mode::PIXEL)
      set_pixel_graphics_mode();

    *(((uint8_t*)0xA0000) + position) = clr;
#endif
  }

  void put_pixel(color clr, const point2d& position)
  {
#if 0
    if (graphics_mode::active_type != graphics_mode::PIXEL)
      set_pixel_graphics_mode();

    real_thunk::put_pixel_params pp;
    pp.hdr.func_type = real_thunk::PUT_PIXEL;
    pp.color = color;
    pp.x = static_cast<uint16_t>(position.x);
    pp.y = static_cast<uint16_t>(position.y);
    real_thunk::func((void*)(&pp), sizeof(pp));
#else
    put_pixel(clr, position.y*cols() + position.x);
#endif
  }

  uint8_t pixel_at(uint position)
  {
#if 0
    return pixel_at(point2d(position % cols(), position / cols()));
#else
    if (graphics_mode::active_type != graphics_mode::PIXEL)
      set_pixel_graphics_mode();

    return *(((uint8_t*)(0xA0000)) + position);
#endif
  }

  uint8_t pixel_at(const point2d& position)
  {
#if 0
    if (graphics_mode::active_type != graphics_mode::PIXEL)
      set_pixel_graphics_mode();

    real_thunk::pixel_at_params pa;
    pa.hdr.func_type = real_thunk::PIXEL_AT;
    pa.x = static_cast<uint16_t>(position.x);
    pa.y = static_cast<uint16_t>(position.y);
    return real_thunk::func((void*)(&pa), sizeof(pa));
#else
    return pixel_at(position.y*cols() + position.x);
#endif
  }
}
